<template>
	<div>
		<div class="userinfo-box">
			<div class="userinfo-tab">
				<a href="javascript:void(0);" @click="basicInfo=true" :class="{active:basicInfo}">基本信息</a>
				<a href="javascript:void(0);" @click="basicInfo=false" :class="{active:!basicInfo}">头像照片</a>
			</div>
			<!-- 基本资料 -->
			<div class="security-setting" v-if="basicInfo">
				<ul>
					<li class="clearfix" v-show="flags">
						<p class="fl front">注册账号</p>
						<p class="txt fl on">
							<input type="text" placeholder="账号" class="inp" v-model="newUserInfo.username" readonly>
						</p>
					</li>
					<li class="clearfix">
						<p class="fl front">昵称</p>
						<p class="txt fl on hastips">
							<input type="text" readonly="true" placeholder="请输入昵称" class="inp" :maxlength="8" v-model="newUserInfo.nickname" ref="inpnickname" :class="{inpwritestyle:!changenicknameShow}">
							<!-- nickname -->
							<span class="nctips" v-show="nullnickname">昵称不能为空</span>
							<span class="nctips" v-show="tipsnickname">只能输入汉字和字母</span>
						</p>
						<p class="tool fr"><a href="javascript:void(0)" class="activeStyle" v-show="changenicknameShow" @click="changeNickname">修改</a></p>
						<p class="tool fr"><a href="javascript:void(0)" class="activeStyle" v-show="!changenicknameShow" @click="changeNickNameok">确定</a></p>
					</li>
					<li class="clearfix">
						<p class="fl front">手机</p>
						<p class="txt fl on">
							<input type="text" class="inp" v-model="newUserInfo.mobile" readonly>
							<!-- <input type="text" placeholder="请绑定手机号码" class="inp" v-model="newUserInfo.mobile" readonly> -->
						</p>
					</li>
					<li class="clearfix">
						<p class="fl front">邮箱</p>
						<p class="txt fl on hastips">
							<input type="text" placeholder="请绑定邮箱" :maxlength="30" readonly="true" class="inp" v-model="newUserInfo.email" ref="inpemail" :class="{inpwritestyle:!changeemailShow}">
							<span class="nctipsqq" v-show="nullemail">邮箱不能为空</span>
							<span class="nctipsqq" v-show="tipsemail">邮箱格式错误</span>
						</p>
						<p class="tool fr"><a href="javascript:void(0)" class="activeStyle" v-show="changeemailShow" @click="changeEmail">修改</a></p>
						<p class="tool fr"><a href="javascript:void(0)" class="activeStyle" v-show="!changeemailShow" @click="changeemailok">确定</a></p>
					</li>
					<li class="clearfix">
						<p class="fl front">微信</p>
						<p class="txt fl on">
							<input type="text" placeholder="请绑定微信" :maxlength="30" readonly="true" class="inp" v-model="newUserInfo.weixin" ref="inpweixin" :class="{inpwritestyle:!changeweiwinShow}">
							<span class="nctipsqq" v-show="nullweixin">微信不能为空</span>
							<span class="nctipsqq" v-show="tipsweixin">微信格式错误</span>
						</p>
						<p class="tool fr"><a href="javascript:void(0)" class="activeStyle" v-show="changeweiwinShow" @click="changeweixin">修改</a></p>
						<p class="tool fr"><a href="javascript:void(0)" class="activeStyle" v-show="!changeweiwinShow" @click="changeweixinok">确定</a></p>
					</li>
					<li class="clearfix">
						<p class="fl front">QQ</p>
						<p class="txt fl on">
							<input type="text" placeholder="请绑定QQ" :maxlength="13" readonly="true" class="inp" v-model="newUserInfo.qq" ref="inpqq" :class="{inpwritestyle:!changeqqShow}">
							<span class="nctipsqq" v-show="nullqq">QQ不能为空</span>
							<span class="nctipsqq" v-show="tipsqq">QQ格式错误</span>
						</p>
						<p class="tool fr"><a href="javascript:void(0)" class="activeStyle" v-show="changeqqShow" @click="changeqq">修改</a></p>
						<p class="tool fr"><a href="javascript:void(0)" class="activeStyle" v-show="!changeqqShow" @click="changeqqok">确定</a></p>
					</li>
					<!-- <li class="clearfix" v-show="flags">
						<p class="fl front">登录密码 <span class="icon icon-suo"></span></p>
						<p class="txt fl">登录账号需要用的密码</p>
						<router-link tag="p" to='securitySetting' class="tool fr activeStyle">重置</router-link>
					</li>
					<li class="clearfix" v-show="flags">
						<p class="fl front">支付密码 <span class="icon icon-suo"></span></p>
						<p class="txt fl">在账号资金变动时需要输入的密码</p>
						<router-link tag="p" to="securitySetting" class="tool fr activeStyle">{{accountData.is_set_paypassword?'重置':'未设置'}}</router-link>
					</li>
					<li class="clearfix" v-show="flags">
						<p class="fl front">银行卡</p>
						<p class="txt fl" v-show="bankedData.bank=='微信'||bankedData.bank=='支付宝'">已添加 <span class="red">{{(bankedData.bank=="微信"||bankedData.bank=="支付宝")?bankedData.bank:'你还没有绑定卡片'}}支付</span> 方式</p>
						<p class="txt fl" v-show="!(bankedData.bank=='微信'||bankedData.bank=='支付宝')"><span class="red">你还没有绑定卡片,请绑定</span></p>
						<router-link tag='p' to="cardManager" class="tool fr activeStyle">管理</router-link>
					</li> -->
				</ul>
			</div>

			<!-- 头像信息 -->
			<div class="fix-img clearfix" v-else>
				<div class="left fl">
					<div class="upload-img">
						<span class="icon icon-upload"></span>选择您要上传的图片
						<input type="file" ref="upload" @change="upAvatar">
					</div>
					<p class="tips">仅支持JPG、GIF、PNG、JPEG、BMP格式，文件小于4M</p>
					<div class="img-box">
						<div class="img-wrap" v-if="avatarImg">
							<canvas class="canvas" style="display:none"></canvas>
							<img :src="avatarImg" alt="">
						</div>
					</div>
					<div class="recommend-img">
						<div class="title">推荐头像</div>
						<ul class="avatar-list clearfix" v-if="avatarList.length">
							<li @click='defaultAvatar(index)' :class="{'active':avatarIndex == index}" v-for="(item,index) in avatarList" :key="index">
							<!-- <li @click='avatarIndex = index' :class="{'active':avatarIndex == index}" v-for="(item,index) in avatarList" :key="index"> -->
								<!-- <img :src="imgRequest+item.avatar_url" alt=""> -->
								<img v-if="item.avatar_url" @error="emptyuserPicUrl(index)" :src="imgRequest + item.avatar_url" alt="">
								<img v-else src="@/assets/images/head_default.png">
							</li>
						</ul>
						<Button type="primary" class="save-btn" :loading="btnLoading" @click="saveAvatar">
							<span v-if="!btnLoading">保存</span>
            				<span v-else>保存中...</span>
						</Button>
					</div>
				</div>

				<div class="right fl">
					<div class="title">效果预览</div>
					<p class="tips">你上传的图片会自动生成2种尺寸，请注意小尺寸的头像是否清晰</p>
					<div class="img-wrap"><img v-if="avatarImg" :src="avatarImg" alt=""></div>
					<p class="tips">100*100像素</p>
					<div class="img-wrap small-img"><img v-if="avatarImg" :src="avatarImg" alt=""></div>
					<p class="tips">50*50像素</p>
				</div>
			</div>
	  
    	</div>
  	</div>
</template>
<script>
import { jsonToString } from "@/common/js/jsonToString";
import loginStore from "../../../store/loginStore";
import { mapGetters, mapActions } from "vuex";
// import { mapActions } from "vuex";
export default {
	data() {
		return {
			flags: '',
			ncnullshow: false,
			nctipsshow: false,

			nullnickname: false,
			tipsnickname: false,
			nullemail: false,
			tipsemail: false,
			nullweixin: false,
			tipsweixin: false,
			nullqq: false,
			tipsqq: false,

			basicInfo: true, //基本资料
			changenicknameShow: true,
			changeemailShow: true,
			changeweiwinShow: true,
			changeqqShow: true,
			nickname: '',
			userInfoFlag: false,
			avatarList: [], //头像列表
			avatarIndex: -1, //默认头像索引
			avatarImg: null,
			username: '',
			newUserInfo: {
				username: '',
				nickname: '',
				mobile: '',
				email: '',
				weixin: '',
				qq: '',
			},
			//已绑定的支付方式

			btnLoading: false,
		};
	},

	created() {
		this.getBankedData();
		this._getAvatarList();
		this.flags = JSON.parse(localStorage.getItem("isUser"));
		if (this.userInfo && this.userInfo.username) {
			// this.newUserInfo = this.userInfo;
			this.newUserInfo = {
				username: this.userInfo.username,
				nickname: this.userInfo.nickname,
				mobile: this.userInfo.mobile,
				email: this.userInfo.email,
				weixin: this.userInfo.weixin,
				qq: this.userInfo.qq
			}
			// this.newUserInfo.username = this.userInfo.username;
			// this.newUserInfo.nickname = this.userInfo.nickname;
			// this.newUserInfo.mobile = this.userInfo.mobile;
			// this.newUserInfo.email = this.userInfo.email;
			// this.newUserInfo.weixin = this.userInfo.weixin;
			// this.newUserInfo.qq = this.userInfo.qq;
		}
		// this.newUserInfo = this.userInfo;
		// console.log('userInfo', this.userInfo)
		// this.$http.post('?m=api&c=user&a=userInfo',{'token':localStorage.getItem("token")}).then(res=>{
		//   this.newUserInfo = res.data.data
		// })
	},
	computed: {
		...mapGetters(["userInfo", "accountData", "bankedData"])
	},
	methods: {
		...mapActions(["SET_ACCOUNT_DATA", "SET_BANKED_DATA",'SET_USER_INFO_DATA']),

		emptyuserPicUrl(index) { //清空红包列表头像路径
			this.avatarList[index].avatar_url = ''
		},
		//获取用户资料
		//修改昵称
		changeNickname: function() {
			this.changenicknameShow = false;
			this.$refs.inpnickname.focus();
			this.$refs.inpnickname.readOnly = false;
			this.userInfoFlag = false;
		},
		changeNickNameok: function() {
			if (this.newUserInfo.nickname == "" || this.newUserInfo.nickname == null) {
				this.nullnickname = true
				this.tipsnickname = false
				return
			}
			if (!/^[A-Za-z\u4e00-\u9fa5]{0,8}$/.test(this.newUserInfo.nickname)) {
				this.nullnickname = false
				this.tipsnickname = true
				return
			}
			this.nullnickname = false
			this.tipsnickname = false

			var params = {
				token: localStorage.getItem("token"),
				nickname: this.newUserInfo.nickname,
			};
			this.$http.post(this.urlRequest + "?m=api&c=user&a=setInfo", params).then(res => {
				if (res.data.status == 0) {
					this.changenicknameShow = true;
					this.$Message.success("修改昵称成功！");
					this.$refs.inpnickname.readOnly = true;
					this.userInfoFlag = true;
					
					let temp = this.userInfo;
					temp["nickname"] = this.newUserInfo.nickname
					this.SET_USER_INFO_DATA({
						Obj: temp
					});
					console.log('userInfo.nickname', this.userInfo)
				} else {
					this.$Message.error(res.data.ret_msg);
				}
			});
		},
		//修改email
		changeEmail: function() {
			this.changeemailShow = false;
			this.$refs.inpemail.focus();
			this.$refs.inpemail.readOnly = false;
			this.userInfoFlag = false;
		},
		changeemailok: function() {
			if (this.newUserInfo.email == "" || this.newUserInfo.email == null) {
				this.nullemail = true
				this.tipsemail = false
				return
			}
			if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(this.newUserInfo.email)) {
				this.nullemail = false
				this.tipsemail = true
				return
			}
			this.nullemail = false
			this.tipsemail = false

			var params = {
				token: localStorage.getItem("token"),
				email: this.newUserInfo.email,
			};
			this.$http.post(this.urlRequest + "?m=api&c=user&a=setInfo", params).then(res => {
				if (res.data.status == 0) {
					this.changeemailShow = true;
					this.userInfo.email = this.userInfo.email;
					this.$Message.success("修改邮箱成功！");
					this.$refs.inpemail.readOnly = true;
					this.userInfoFlag = true;

					let temp = this.userInfo;
					temp["email"] = this.newUserInfo.email
					this.SET_USER_INFO_DATA({
						Obj: temp
					});
					console.log('userInfo.email', this.userInfo)
				} else {
					this.$Message.error(res.data.ret_msg);
				}
			});
		},
		//修改微信
		changeweixin: function() {
			this.changeweiwinShow = false;
			this.$refs.inpweixin.focus();
			this.$refs.inpweixin.readOnly = false;
			this.userInfoFlag = false;
		},
		changeweixinok: function() {
			if (this.newUserInfo.weixin == "" || this.newUserInfo.weixin == null) {
				this.nullweixin = true
				this.tipsweixin = false
				return
			}
			if (!/^[a-zA-Z0-9_-]{3,30}$/.test(this.newUserInfo.weixin)) {
				this.nullweixin = false
				this.tipsweixin = true
				return
			}
			this.nullweixin = false
			this.tipsweixin = false
			var params = {
				token: localStorage.getItem("token"),
				weixin: this.newUserInfo.weixin,
			};
			this.$http.post(this.urlRequest + "?m=api&c=user&a=setInfo", params).then(res => {
				if (res.data.status == 0) {
					this.changeweiwinShow = true;
					this.userInfo.weixin = this.userInfo.weixin;
					this.$Message.success("修改微信成功！");
					this.$refs.inpweixin.readOnly = true;
					this.userInfoFlag = true;
					
					let temp = this.userInfo;
					temp["weixin"] = this.newUserInfo.weixin
					this.SET_USER_INFO_DATA({
						Obj: temp
					});
					console.log('userInfo.weixin', this.userInfo)
				} else {
					this.$Message.error(res.data.ret_msg);
				}
			});
		},
		//修改QQ
		changeqq: function() {
			this.changeqqShow = false;
			this.$refs.inpqq.focus();
			this.$refs.inpqq.readOnly = false;
			this.userInfoFlag = false;
		},
		changeqqok: function() {
			if (this.newUserInfo.qq == "" || this.newUserInfo.qq == null) {
				this.nullqq = true
				this.tipsqq = false
				return
			}
			if (!/^[1-9]{1}[0-9]{4,12}$/.test(this.newUserInfo.qq)) {
				this.nullqq = false
				this.tipsqq = true
				return
			}
			this.nullqq = false
			this.tipsqq = false
			var params = {
				token: localStorage.getItem("token"),
				qq: this.newUserInfo.qq,
			};
			this.$http.post(this.urlRequest + "?m=api&c=user&a=setInfo", params).then(res => {
				if (res.data.status == 0) {
					this.changeqqShow = true;
					this.userInfo.qq = this.userInfo.qq;
					this.$Message.success("修改QQ成功！");
					this.$refs.inpqq.readOnly = true;
					this.userInfoFlag = true;
					
					let temp = this.userInfo;
					temp["qq"] = this.newUserInfo.qq
					this.SET_USER_INFO_DATA({
						Obj: temp
					});
					console.log('userInfo.qq', this.userInfo)
				} else {
					this.$Message.error(res.data.ret_msg);
				}
			});
		},
		//获取头像数据
		_getAvatarList(){
			var params = {};
				params.token = localStorage.getItem("token");
				params.avatar_num = "9";
			this.$http.post(this.urlRequest + "?m=api&c=avatar&a=avatarList", params).then(res => {
				if (res.data.status == 0) {
					this.avatarList = res.data.avatar_list;
				} else {
					this.$Message.error(res.data.ret_msg);
				}
			});
		},
		upAvatar() { //获取上传按钮
			this.avatarIndex = -1
			// var input1 = document.getElementById("upload"); 
			let vm = this;
			let maxSize = 4;
			let upload = this.$refs.upload;
			var file = upload.files[0];//获取上传文件列表中第一个文件
			if (!/\.(?:JPG|GIF|PNG|JPEG|BMP)$/i.test(file.name)) {
				//仅支持JPG、GIF、PNG、JPEG、BMP格式
				// alert("文件必须为图片！");
				this.$Message.error("仅支持JPG、GIF、PNG、JPEG、BMP格式");
				return false; 
			}
			if (file.size > maxSize * 1024 *1024) {
				this.$Message.error("图片大小超过限制,请限制在" + maxSize + "M以内");
				return false;
			}
			// var reader = new FileReader();//实例一个文件对象
			// reader.readAsDataURL(file);//把上传的文件转换成url
			
			//当文件读取成功便可以调取上传的接口
			var image = new Image();
			// 设置src属性 
			image.src = vm.getObjectURL(file);
			// 绑定load事件处理器，加载完成后执行，避免同步问题
			image.onload = function() {
				vm.avatarImg = vm.getBase64Image(image);
			};     
		},
		getObjectURL(file) {
			var url = null;
			if (window.createObjectURL != undefined) { // basic
				url = window.createObjectURL(file);
			} else if (window.URL != undefined) { // mozilla(firefox)
				url = window.URL.createObjectURL(file);
			} else if (window.webkitURL != undefined) { // webkit or chrome
				url = window.webkitURL.createObjectURL(file);
			}
			return url;
		},
		getBase64Image(img) {  
			var canvas = document.createElement("canvas");  
			canvas.width = 150;  
			canvas.height = 150;  
			var ctx = canvas.getContext("2d");  
			ctx.drawImage(img, 0, 0, 150, 150);  
			var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();  
			var dataURL = canvas.toDataURL("image/"+ext);  
			return dataURL;  
		},  
		defaultAvatar(index) {
			this.avatarIndex = index
			this.avatarImg = ''
			this.$refs.upload.value = ''
		},
		//保存头像
		saveAvatar: function() {
			if (this.avatarIndex == -1 && !this.avatarImg) {
				this.$Message.error('请选择头像');
				return;
			}
			this.btnLoading = true;
			if (this.avatarImg) {
				var params = {};
					params.token = localStorage.getItem("token");
					// params.avatar = this.avatarImg
					params.avatar = this.avatarImg.split(",")[1];
				this.$http.post(this.urlRequest + "?m=api&c=user&a=saveAvatar", params).then(res => {
					this.btnLoading = false;
					if (res.data.status == 0) {
						// this.avatarList = res.data.avatar_list;
						this.$Message.success("保存成功");
						this.userInfo.avatar = res.data.avatar;
					} else {
						this.$Message.error(res.data.ret_msg);
					}
				}).catch(error => {
					this.btnLoading = false;
					this.$Message.error("数据请求超时");
				});
			} else {
				var params = {};
					params.token = localStorage.getItem("token");
					params.avatar_url = this.avatarList[this.avatarIndex].avatar_url;
				this.$http.post(this.urlRequest + "?m=api&c=user&a=saveDefaultAvatar", params).then(res => {
					this.btnLoading = false;
					if (res.data.status == 0) {
						// this.avatarList = res.data.avatar_list;
						this.$Message.success("保存成功");
						this.userInfo.avatar = res.data.avatar_url;
					} else {
						this.$Message.error(res.data.ret_msg);
					}
				}).catch(error => {
					this.btnLoading = false;
					this.$Message.error("数据请求超时");
				});
			}
		},
		//查询是否绑银行卡
		getBankedData: function() {
			var params = {
				token: localStorage.getItem("token")
			};
			this.$http.post(this.urlRequest + "?m=api&c=bank&a=getUserBank", params).then(res => {
				localStorage.setItem("bankedData", JSON.stringify(res.data));
				this.SET_BANKED_DATA({
					obj: res.data
				});
			});
		},
	},
	watch: {   
		userInfo(obj) {
			if (obj.username) {
			// this.newUserInfo = this.userInfo;
			this.newUserInfo = {
				username: this.userInfo.username,
				nickname: this.userInfo.nickname,
				mobile: this.userInfo.mobile,
				email: this.userInfo.email,
				weixin: this.userInfo.weixin,
				qq: this.userInfo.qq
			}
			// this.newUserInfo.username = this.userInfo.username;
			// this.newUserInfo.mobile = this.userInfo.mobile;
			// this.newUserInfo.nickname = this.userInfo.nickname;
			// this.newUserInfo.email = this.userInfo.email;
			// this.newUserInfo.weixin = this.userInfo.weixin;
			// this.newUserInfo.qq = this.userInfo.qq;
			}
			// if(JSON.stringify(obj) != '{}'){
			//   this.newUserInfo = JSON.parse(JSON.stringify(obj));
			// }
		}
    }
};
</script>
<style scoped>
.pc-cont {
  	padding-top: 0px;
}
.activeStyle:hover {
  	color: #f3596a;
}
.nctipsqq {
	position: absolute;
	top: 30px;
	color: #f3596a;
	width: 100px;
}
.inp.inpwritestyle {
  border: 1px solid #ccc;
  border-radius: 5px;
  border-color: #2d8cf0;
}
.inp {
  	color: #999;
}
.nctips {
	position: absolute;
	top: 25px;
	color: #f3596a;
}
.hastips {
  	width: 206px;
}
.avatar-list li {
	float: left;
	cursor: pointer;
	margin-right: 8px;
	margin-bottom: 10px;
	width: 44px;
	height: 44px;
	padding: 2px;
	border-radius: 50%;
	border: 1px solid #eee;
}
.avatar-list li:hover,
.avatar-list li.active {
  	border-color: #f3596a;
}
.avatar-list li img {
	width: 38px;
	height: 38px;
}
.img-wrap {
	border-radius: 50%;
}
.save-btn {
  	min-width: 80px;
}
</style>





// WEBPACK FOOTER //
// src/components/PersonalCenter/personalInfo/personalInfo.vue